package com.cfc.stage1;

import common.ArrayGenerate;
import org.junit.Test;

/**
 * @description: 寻找两个正序数组的中位数
 *   https://leetcode.cn/problems/median-of-two-sorted-arrays/description/
 * @author: yangxuan10
 * @create: 2024-05-23 14:26
 **/
public class FindMedianSortedArrays {

    @Test
    public void test1() {
        System.out.println(3d/2);
        int[] ints = ArrayGenerate.strConvertIntArray("1,2");
        int[] ints1 = ArrayGenerate.strConvertIntArray("3,4");
        System.out.println(findMedianSortedArrays(ints,ints1));
    }

    //TODO

    /**
     * 原创
     * @param nums1
     * @param nums2
     * @return
     */
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int length1 = nums1.length;
        int length2 = nums2.length;
        int merge = length1 + length2;
        int mid = merge / 2;
        int oddNumberEven = merge % 2;

        int index1 = 0,index2 =0;
        int temp = 0;
        double target = 0D;
        for (int i = 0 ;i <= mid; i++) {

            if (index2 == length2 || (index1 < length1 && nums1[index1] <= nums2[index2])) {
                temp  = nums1[index1];
                index1 ++;
            } else if (index1 == length1 || (index2 < length2 && nums1[index1] > nums2[index2])) {
                temp = nums2[index2];
                index2 ++;
            }
            if (oddNumberEven == 0 && i == mid -1) {
                target = temp;
            }
            if (i == mid) {
                target += temp;
            }
        }
        return oddNumberEven == 0 ? target / 2 : target;
    }

}